package com.ciei.dpagm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ciei.dpagm.entity.*;
import com.ciei.dpagm.common.converter.JsonConverter;
import com.ciei.dpagm.common.service.BaseService;
import com.ciei.dpagm.util.*;
import com.ciei.dpagm.mapper.SupplierMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author pp
 * @date 2020/8/31 11:09
 **/
@Service
public class SupplierService extends BaseService<SupplierMapper, Supplier> {

    @Autowired
    private AreaService areaService;
    @Autowired
    private FilesService filesService;
    @Autowired
    private SupplyTypeService supplyTypeService;
    @Autowired
    private FileTypeService fileTypeService;


    public JSONObject loadSupplieDataVue(PageParam ps) {
        Map<String, Object> params=ps.getParams();
        JSONObject json = new JSONObject();
        int currentPage =ps.getCurrentPage();
        int pageSize =ps.getPageSize();
        IPage<Supplier> page = findPageVue(currentPage, pageSize, params, new String[]{"name"}, null, null,null);
        List<Supplier> list= page.getRecords();
        JSONArray jarr = new JSONArray();
        if(list.size()>0){
            List<SupplyType> supplyTypeAll = supplyTypeService.findListByIds(list.stream().map(Supplier::getSupplyTypeId).collect(Collectors.toSet()));
            List<FileType> fileTypesAll = fileTypeService.findAll();
            for (Supplier res : list) {
                Map<String, Object> mobj = new HashMap<String, Object>();
                mobj.put("id", res.getId());
                mobj.put("name", res.getName());
                mobj.put("supplies", res.getSupplies());
                mobj.put("province", res.getProvince());
                mobj.put("city", res.getCity());
                mobj.put("country", res.getCountry());
                if(res.getAreaId()!=null){
                    String areaId = String.valueOf(res.getAreaId());
                    mobj.put("countryId", Integer.valueOf(areaId));
                    mobj.put("cityId", Integer.valueOf(areaId.substring(0, 4)+"00"));
                    mobj.put("provinceId", Integer.valueOf(areaId.substring(0, 3)+"000"));
                }
                mobj.put("address", res.getAddress());
                mobj.put("date", res.getAssessDate());
                mobj.put("assessScore", res.getAssessScore());
                mobj.put("remark", res.getRemark());
                //先查询评审表，评审表与供应类型分开
                SupplyType supplyTy = supplyTypeAll.stream()
                        .filter(s -> s.getId().equals(res.getSupplyTypeId()))
                        .findFirst()
                        .orElse(null);
                JSONArray ja = new JSONArray();
                if(supplyTy!=null){
                    ja.add(supplyTy.getParentId());
                    ja.add((supplyTy.getId()));
                }
                mobj.put("supplyTypeId", ja);
                JSONArray jsonArr = new JSONArray();
                Map<String,Object> m = new HashMap<>();
                FileType fileTy = fileTypesAll.stream()
                        .filter(f -> f.getId().equals(3))
                        .findFirst()
                        .orElse(null);
                m.put("relationId",res.getId());
                m.put("relationTypeId",fileTy.getId());
            /*List<Files> filesLi = filesAll.stream()
                    .filter(f -> f.getRelationTypeId()==3 && f.getRelationId().equals(res.getId()))
                    .collect(Collectors.toList());*/
                List<Files> filesLi=filesService.findByProperties(new String[]{"relationTypeId","relationId"},new Integer[]{3,res.getId()});
                if(filesLi.size()>0){
                    Files files = filesLi.get(filesLi.size() - 1);
                    m.put("name",files.getFileName());
                    m.put("url",files.getPath());
                    m.put("fileType",files.getFileType());
                    m.put("fileId",files.getFileId());
                    jsonArr.add(m);
                    mobj.put(fileTy.getCode(),jsonArr);
                }

                if(res.getSupplyTypeId()!=null){
                    Integer supplyTypeId = res.getSupplyTypeId();
                    SupplyType supplyType = supplyTypeAll.stream()
                            .filter(s -> s.getId().equals(supplyTypeId))
                            .findFirst()
                            .orElse(null);
                    String fileTypes = supplyType.getFileTypes();
                    if(!"".equals(fileTypes)){
                        String[] fileTypeIdList = fileTypes.split(",");
                        Integer[] ints = new Integer[fileTypeIdList.length];
                        for(int i=0;i<fileTypeIdList.length;i++){
                            ints[i] = Integer.parseInt(fileTypeIdList[i]);
                        }
                        List<FileType> fileTypeList = fileTypeService.findByIds(ints);
                        for(FileType fileType : fileTypeList){
                            JSONArray jsonArray = new JSONArray();
                            Map<String,Object> map = new HashMap<>();
                            map.put("relationId",res.getId());
                            map.put("relationTypeId",fileType.getId());
                            List<Files> filesList = filesService.findByProperties(new String[]{"relationTypeId", "relationId"}, new Integer[]{fileType.getId(),res.getId()});
                            //前端文件数据格式[{文件数据}],文件数据可参考FileService的上传文件数据
                            if(filesList.size()>0){
                                Files files = filesList.get(filesList.size() - 1);
                                map.put("name",files.getFileName());
                                map.put("url",files.getPath());
                                map.put("fileType",files.getFileType());
                                map.put("fileId",files.getFileId());
                                jsonArray.add(map);
                                //前端不同文件给的键都是唯一的，数据库也没值可判断
                                if(supplyType.getId()==3){
                                    switch (fileType.getId()){
                                        case 4:
                                            mobj.put("calibrationBusinessLicense",jsonArray);
                                            break;
                                        case 5:
                                            mobj.put("calibrationCapability",jsonArray);
                                            break;
                                        case 6:
                                            mobj.put("CNASCertificate",jsonArray);
                                            break;
                                        case 7:
                                            mobj.put("testingQualificationCertificate",jsonArray);
                                            break;
                                        case 8:
                                            mobj.put("traceabilityOfCalibrationEquipment",jsonArray);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                if(supplyType.getId()==5){
                                    switch (fileType.getId()){
                                        case 6:
                                            mobj.put("capabilityVerificationBusinessLicense",jsonArray);
                                            break;
                                        case 13:
                                            mobj.put("CNASProficiencyTestingProviderCertificate",jsonArray);
                                            break;
                                        case 9:
                                            mobj.put("scopeOfProficiencyTesting",jsonArray);
                                            break;
                                        default:
                                            break;
                                    }

                                }
                                if(supplyType.getId()==9){
                                    switch (fileType.getId()){
                                        case 4:
                                            mobj.put("deviceBusinessLicense",jsonArray);
                                            break;
                                        case 10:
                                            mobj.put("deviceSystemCertificationCertificate",jsonArray);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                if(supplyType.getId()==10){
                                    switch (fileType.getId()){
                                        case 4:
                                            mobj.put("consumableBusinessLicense",jsonArray);
                                            break;
                                        case 11:
                                            mobj.put("consumableInspectionReport",jsonArray);
                                            break;
                                        case 12:
                                            mobj.put("productionLicense",jsonArray);
                                            break;
                                        case 10:
                                            mobj.put("consumableSystemCertificationCertificate",jsonArray);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                        }
                    }
                }
                jarr.add(mobj);
            }
        }
        json.put(APP.DATA, jarr);
        json.put(APP.TOTAL_COUNT, page.getTotal());
        json.put(APP.POS, (currentPage - 1) * pageSize);
        json.put(APP.CURRENT_PAGE, page.getCurrent());
        return json;
    }

    /**
     * 加载供应商对应的附件数据
     * @param ps
     * @return
     */
    public JSONObject loadFileVue(PageParam ps) {
        JSONObject json = new JSONObject();
        JSONArray jarr = new JSONArray();
        Map<String, Object> params=ps.getParams();
        int currentPage =ps.getCurrentPage();
        int pageSize =ps.getPageSize();
        if(params.get("id")!=null){
            Integer id = (Integer) params.get("id");
            Supplier supplier = findById(id);
            SupplyType supplyType = supplyTypeService.findById(supplier.getSupplyTypeId());
            String fileTypes = supplyType.getFileTypes();
            List<Integer> fileList = new ArrayList<>();
            List<FileType> fileTypeAll = fileTypeService.findAll();
            if(!"".equals(fileTypes)) {
                String[] fileTypeIdList = fileTypes.split(",");
                Integer[] ints = new Integer[fileTypeIdList.length];
                for (int i = 0; i < fileTypeIdList.length; i++) {
                    ints[i] = Integer.parseInt(fileTypeIdList[i]);
                }
                List<FileType> fileTypeList = fileTypeService.findByIds(ints);
                for(FileType fileType : fileTypeList){
                    fileList.add(fileType.getId());
                }
            }
            //评审表
            fileList.add(3);
            if(params.get("name")!=null){
                params.put("fileName",params.get("name"));
            }
            params.put("relationTypeId",fileList);
            params.put("relationId",id);
            IPage<Files> page = filesService.findPageVue(currentPage, pageSize, params, new String[]{"fileName"}, new String[]{"relationId"}, null,new String[]{"relationTypeId"});
            List<Files> list= page.getRecords();
            if(list.size()>0) {
                for (Files files : list) {
                    Map<String, Object> map = new HashMap<>();
                    FileType fileType = fileTypeAll.stream()
                            .filter(f -> f.getId().equals(files.getRelationTypeId()))
                            .findFirst()
                            .orElse(null);
                    map.put("name", files.getFileName());
                    map.put("url", files.getPath());
                    map.put("fileId", files.getFileId());
                    map.put("type", fileType.getName());
                    jarr.add(map);
                }
            }
            json.put(APP.DATA, jarr);
            json.put(APP.TOTAL_COUNT, page.getTotal());
            json.put(APP.POS, (currentPage - 1) * pageSize);
            json.put(APP.CURRENT_PAGE, page.getCurrent());
        }else{
            json= JsonUtil.getFail("供应商id不能为空,查询失败");
        }
        return json;
    }


    public JSONObject addOrUpdateSupplie(JSONObject jsonObject,String type, Users user) {
        JSONObject json = null;
        String[] propertyNames = {"name"};
        String[] values = {jsonObject.getString("name")};
        List<Supplier> supplierList=new ArrayList<>();
        if("add".equals(type)){
            supplierList=findByProperties(propertyNames, values);
            if(supplierList.size()>0){
                json = JsonUtil.getFail("公司已存在,添加失败!");
            }
        }else{
            supplierList=findByPropertiesNotSelf(propertyNames, values, jsonObject.getInteger("id"));
            if(supplierList.size()>0){
                json = JsonUtil.getFail("公司已存在,更新失败!");
            }
        }
        if(supplierList.size()==0 ) {
            JsonConverter<Supplier> jsonConverter = new JsonConverter<>();
            if (jsonObject.getJSONArray("supplyTypeId")!=null){
                JSONArray supplyTypeId = jsonObject.getJSONArray("supplyTypeId");
                if(supplyTypeId.size()>0){
                    jsonObject.put("supplyTypeId", supplyTypeId.get(1));
                }else {
                    jsonObject.put("supplyTypeId", null);
                }
            } else {
                jsonObject.put("supplyTypeId", null);
            }

            Supplier supplier = new Supplier();
            if (StringUtils.isNotBlank(jsonObject.getString("date"))){
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    supplier.setAssessDate(f.parse(jsonObject.getString("date")));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            supplier = jsonConverter.convert(jsonObject, supplier);
            if (jsonObject.getInteger("countryId") != null) {
                Integer countryId = jsonObject.getInteger("countryId");
                List<Area> countryAreas = areaService.findByProperty("areaId", countryId);
                supplier.setCountry(countryAreas.get(0).getAreaName());
                supplier.setAreaId(countryId);
            }
            if (jsonObject.getInteger("cityId") != null) {
                List<Area> cityAreas = areaService.findByProperty("areaId", jsonObject.getInteger("cityId"));
                supplier.setCity(cityAreas.get(0).getAreaName());
            }
            if (jsonObject.getInteger("provinceId") != null) {
                List<Area> provinceAreas = areaService.findByProperty("areaId", jsonObject.getInteger("provinceId"));
                supplier.setProvince(provinceAreas.get(0).getAreaName());
            }
            //前端传的文件为一个数组，键为code，每一个文件都有不同的code，每次添加都不确定有多少code，
            // 所以将全部的code都做一次非空判断，有数据的就将该文件添加到list
            List<Files> filesList = new ArrayList<>();
            filesList = propAdd("assessForm", jsonObject, user,filesList,3,supplier.getId());
            filesList = propAdd("calibrationBusinessLicense", jsonObject, user,filesList,4,supplier.getId());
            filesList = propAdd("calibrationCapability", jsonObject, user,filesList,5,supplier.getId());
            filesList = propAdd("CNASCertificate", jsonObject, user,filesList,6,supplier.getId());
            filesList = propAdd("testingQualificationCertificate", jsonObject, user,filesList,7,supplier.getId());
            filesList = propAdd("traceabilityOfCalibrationEquipment", jsonObject, user,filesList,8,supplier.getId());
            filesList = propAdd("capabilityVerificationBusinessLicense", jsonObject, user,filesList,6,supplier.getId());
            filesList = propAdd("CNASProficiencyTestingProviderCertificate", jsonObject, user,filesList,13,supplier.getId());
            filesList = propAdd("scopeOfProficiencyTesting", jsonObject, user,filesList,9,supplier.getId());
            filesList = propAdd("deviceBusinessLicense", jsonObject, user,filesList,4,supplier.getId());
            filesList = propAdd("deviceSystemCertificationCertificate", jsonObject, user,filesList,10,supplier.getId());
            filesList = propAdd("consumableBusinessLicense", jsonObject, user,filesList,4,supplier.getId());
            filesList = propAdd("consumableInspectionReport", jsonObject, user,filesList,11,supplier.getId());
            filesList = propAdd("productionLicense", jsonObject, user,filesList,12,supplier.getId());
            filesList = propAdd("consumableSystemCertificationCertificate", jsonObject, user,filesList,10,supplier.getId());

            if ("add".equals(type)) {
                save(supplier);
                for (Files file : filesList) {
                    file.setRelationId(supplier.getId());
                }
                filesService.insertBatchSomeColumn(filesList);
                json = JsonUtil.getSuccess("添加成功");
            } else {
                List<Files> savaFiles = new ArrayList<>();
                for(Files files :filesList){
                    if(files.getFileId()==null){
                        savaFiles.add(files);
                        filesService.removeFile(files.getRelationTypeId(),files.getRelationId());
                    }
                }
                if(savaFiles.size()>0){
                    filesService.insertBatchSomeColumn(savaFiles);
                }
                updateById(supplier);
                json = JsonUtil.getSuccess("更新成功");
            }
        }

        return json;
    }

    /**
     * 多条件等值查询并且忽略自己
     *
     * @param propertyNames 属性名数组
     * @param values        属性值数组
     * @return 满足条件的所有记录
     */
    public List<Supplier> findByPropertiesNotSelf(String[] propertyNames, Object[] values,Integer id) {

        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        propertyNames = ConvertUtil.humpToLines(propertyNames);
        if (propertyNames != null) {
            for (int i = 0; i < propertyNames.length; i++) {
                if (values[i] != null) {
                    wrapper.eq(propertyNames[i], values[i]);
                } else {
                    wrapper.isNull(propertyNames[i]);
                }
            }
        }
        if(id!=null){
            wrapper.notIn("id",id);
        }
        return list(wrapper);
    }
    /**
     * 前端传入不同类型的文件都用不同的键来代替
     * 该方法判断如果键不为null就加该文件统一保存
     */
    public List<Files> propAdd(String prop, JSONObject jsonObject, Users user, List<Files> filesList, Integer relationTypeId, Integer relationId){
        if(jsonObject.getJSONArray(prop)!=null){
            if(jsonObject.getJSONArray(prop).isEmpty()){
                filesService.removeFile(relationTypeId,relationId);
            }else{
                JSONArray list = jsonObject.getJSONArray(prop);
                if(list.size()>0){
                    for(int i =0;i<list.size();i++){
                        JSONObject fileData = list.getJSONObject(i);
                        Files files = new Files();
                        if(!"null".equals(fileData.getString("relationId"))){
                            files.setRelationId(Integer.valueOf(fileData.getString("relationId")));
                        }
                        if(!"null".equals(fileData.getString("relationTypeId"))){
                            files.setRelationTypeId(Integer.valueOf(fileData.getString("relationTypeId")));
                        }
                        if(!"".equals(fileData.getString("fileType"))){
                            files.setFileType(fileData.getString("fileType"));
                        }
                        files.setUploadTime(DateUtil.getTimestamp(new Date()));
                        files.setUploadUserId(user.getUserId());
                        if(!"".equals(fileData.getString("url"))){
                            files.setPath(fileData.getString("url"));
                        }
                        if(!"".equals(fileData.getString("name"))){
                            files.setFileName(fileData.getString("name"));
                        }
                        if(fileData.getInteger("fileId")!=null){
                            files.setFileId(fileData.getInteger("fileId"));
                        }
                        filesList.add(files);
                    }
                }

            }
        }
        return filesList;
    }


    public JSONObject deleteVue(JSONObject jsonObject){
        JSONObject json;
        if(jsonObject.getInteger("id")!=null){
            removeById(jsonObject.getInteger("id"));
            json = JsonUtil.getSuccess("删除成功!");
        }else{
            json = JsonUtil.getFail("删除失败,请选择要删除的数据");
        }
        return json;
    }
    public JSONObject exportVue(String baseFilePath,JSONArray jsonArray) {
        List<Integer> ids = new ArrayList<>();
        for(int i = 0; i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            ids.add(jsonObject.getInteger("id"));
        }
        //存供应商数据表
        List<Supplier> supplierList = findByIds(ids);
        return export(baseFilePath, supplierList);
    }
    /**
     *
     *
     * @param id id属性值数组
     * @return 满足条件的所有记录
     */
    public List<Supplier> findByIds(List<Integer> id) {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        if (id != null && id.size()>0) {
            wrapper.in("id", id);
        }
        return list(wrapper);
    }
    public JSONObject exportAllVue(String baseFilePath) {
        //存供应商数据表
        List<Supplier> supplierList = findAll();
        return export(baseFilePath, supplierList);
    }
    public JSONObject export(String baseFilePath,List<Supplier> supplierList) {
        JSONObject json = new JSONObject();
        if (supplierList != null && supplierList.size()>0){
            String[] title = {"供应商", "供应品/服务","供应类型","省","市","县","地址", "评估日期","评分","备注"};
            //excel文件名
            String fileName = "供应商信息表.xls";
            //sheet名
            String sheetName = "供应商信息表";
            String [][] content = new String[supplierList.size()][6];
            List<SupplyType> supplyTypeList = supplyTypeService.findAll();
            for (int i = 0; i < supplierList.size(); i++) {
                content[i] = new String[title.length];
                Supplier supplier = supplierList.get(i);
                content[i][0] = supplier.getName();
                content[i][1] = supplier.getSupplies();
                SupplyType supplyTy = supplyTypeList.stream()
                        .filter(s -> s.getId().equals(supplier.getSupplyTypeId()))
                        .findFirst()
                        .orElse(null);
                if(supplyTy!=null){
                    content[i][2] = supplyTy.getName();
                }
                content[i][3] = supplier.getProvince();
                content[i][4] = supplier.getCity();
                content[i][5] = supplier.getCountry();
                content[i][6] = supplier.getAddress();
                content[i][7] = DateUtil.dateToString(supplier.getAssessDate(),DateUtil.FORMAT_SHORT);
                content[i][8] = String.valueOf(supplier.getAssessScore());
                content[i][9] = supplier.getRemark();
            }
            //创建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
            //设置列宽度
            HSSFSheet sheet = wb.getSheet(sheetName);
            sheet.setColumnWidth(0, 25*256);
            sheet.setColumnWidth(1, 10*256);
            sheet.setColumnWidth(2, 10*256);
            sheet.setColumnWidth(3, 10*256);
            sheet.setColumnWidth(4, 20*256);
            sheet.setColumnWidth(5, 10*256);
            sheet.setColumnWidth(6, 40*256);
            sheet.setColumnWidth(7, 20*256);
            sheet.setColumnWidth(9, 40*256);

            //设置文本居中
            HSSFCellStyle cellStyle = wb.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 第六步，将文件存到指定位置
            try {
                File filePath = new File(baseFilePath+"supplier/");
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }

                File file = new File(baseFilePath+"supplier/"+fileName);
                if(file.exists()){
                    file.delete();
                }
                FileOutputStream fout = new FileOutputStream(baseFilePath+"supplier/"+fileName);
                wb.write(fout);
                fout.close();
   /*             File dataPath = new File(baseFilePath+"供应商资料.zip");
                if(dataPath.exists()){
                    dataPath.delete();
                }
                FileOutputStream fos1 = new FileOutputStream(new File(baseFilePath+"供应商资料.zip"));
                ZipUtil.toZip(baseFilePath+"company", fos1,true);
                json = JsonUtil.getSuccess("导出成功");*/
                json.put("url","uploads/supplier/"+fileName);
            } catch (Exception e) {
                e.printStackTrace();
                json = JsonUtil.getFail("异常，导出失败");
            }
            return  json;
        }else {
            json = JsonUtil.getFail("暂无数据可导出");
            return json;
        }
    }

    /**
     * 查找供应商
     * @return
     */
    public JSONObject findSupplier(){
        JSONObject json = JsonUtil.getSuccess("");
        JSONArray jarr = new JSONArray();
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        List<Supplier> list = list(wrapper);
        if (list != null && list.size()>0){
            for(Supplier supplier:list){
                HashMap<String, Object> map = new HashMap<>(16);
                map.put("text",supplier.getName());
                map.put("value",supplier.getId());
                jarr.add(map);
            }
        }
        json.put(APP.DATA,jarr);
        return json;

    }
}
